<template>
  <div class="parameter-optimization">
    <div class="page-header">
      <h1>模型参数优化</h1>
      <p>调整和优化AI模型的超参数配置</p>
    </div>

    <div class="optimization-content">
      <!-- 参数配置 -->
      <div class="parameter-config">
        <div class="config-section">
          <h3>🎛️ 当前参数配置</h3>
          <div class="parameter-grid">
            <div class="param-item">
              <label>学习率 (Learning Rate)</label>
              <input type="number" v-model="parameters.learningRate" step="0.001" min="0.001" max="1">
              <span class="param-value">{{ parameters.learningRate }}</span>
            </div>
            <div class="param-item">
              <label>批次大小 (Batch Size)</label>
              <input type="number" v-model="parameters.batchSize" step="1" min="1" max="512">
              <span class="param-value">{{ parameters.batchSize }}</span>
            </div>
            <div class="param-item">
              <label>训练轮数 (Epochs)</label>
              <input type="number" v-model="parameters.epochs" step="1" min="1" max="1000">
              <span class="param-value">{{ parameters.epochs }}</span>
            </div>
            <div class="param-item">
              <label>正则化系数 (Regularization)</label>
              <input type="number" v-model="parameters.regularization" step="0.001" min="0" max="1">
              <span class="param-value">{{ parameters.regularization }}</span>
            </div>
            <div class="param-item">
              <label>dropout率</label>
              <input type="number" v-model="parameters.dropout" step="0.1" min="0" max="1">
              <span class="param-value">{{ parameters.dropout }}</span>
            </div>
            <div class="param-item">
              <label>优化器</label>
              <select v-model="parameters.optimizer">
                <option value="adam">Adam</option>
                <option value="sgd">SGD</option>
                <option value="rmsprop">RMSprop</option>
              </select>
              <span class="param-value">{{ parameters.optimizer }}</span>
            </div>
          </div>
          <div class="config-actions">
            <button @click="resetParameters" class="btn btn-secondary">重置参数</button>
            <button @click="saveParameters" class="btn btn-primary">保存配置</button>
            <button @click="startOptimization" class="btn btn-success">开始优化</button>
          </div>
        </div>

        <!-- 优化历史 -->
        <div class="optimization-history">
          <h3>📊 优化历史</h3>
          <div class="history-list">
            <div class="history-item" v-for="(item, index) in optimizationHistory" :key="index">
              <div class="history-header">
                <span class="history-date">{{ item.date }}</span>
                <span class="history-status" :class="item.status">{{ item.status }}</span>
              </div>
              <div class="history-details">
                <p>学习率: {{ item.params.learningRate }}, 批次: {{ item.params.batchSize }}</p>
                <p>准确率: {{ item.accuracy }}%, 损失: {{ item.loss }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 优化结果 -->
      <div class="optimization-results">
        <div class="result-section">
          <h3>📈 性能对比</h3>
          <div class="performance-chart">
            <div ref="performanceComparisonChart" class="chart-container"></div>
          </div>
        </div>

        <div class="result-section">
          <h3>🎯 最优参数推荐</h3>
          <div class="recommendations">
            <div class="recommendation-item">
              <h4>建议配置 #1</h4>
              <div class="config-details">
                <p>学习率: 0.001, 批次: 64, 轮数: 100</p>
                <p>预期准确率: 96.5%</p>
              </div>
              <button @click="applyRecommendation(1)" class="btn btn-outline">应用此配置</button>
            </div>
            <div class="recommendation-item">
              <h4>建议配置 #2</h4>
              <div class="config-details">
                <p>学习率: 0.0005, 批次: 128, 轮数: 150</p>
                <p>预期准确率: 95.8%</p>
              </div>
              <button @click="applyRecommendation(2)" class="btn btn-outline">应用此配置</button>
            </div>
          </div>
        </div>

        <div class="result-section">
          <h3>⚡ 优化建议</h3>
          <div class="optimization-tips">
            <div class="tip-item">
              <h4>💡 学习率调整</h4>
              <p>当前学习率可能过高，建议降低至0.001以获得更稳定的收敛</p>
            </div>
            <div class="tip-item">
              <h4>💡 批次大小优化</h4>
              <p>增加批次大小可以提高训练稳定性，但需要更多GPU内存</p>
            </div>
            <div class="tip-item">
              <h4>💡 正则化建议</h4>
              <p>适度增加正则化系数可以减少过拟合风险</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'ParameterOptimization',
  data() {
    return {
      chartInstance: null,
      parameters: {
        learningRate: 0.001,
        batchSize: 32,
        epochs: 100,
        regularization: 0.01,
        dropout: 0.2,
        optimizer: 'adam'
      },
      optimizationHistory: [
        {
          date: '2024-01-15 14:30',
          status: 'completed',
          params: { learningRate: 0.001, batchSize: 64 },
          accuracy: 94.5,
          loss: 0.125
        },
        {
          date: '2024-01-14 10:15',
          status: 'completed',
          params: { learningRate: 0.005, batchSize: 32 },
          accuracy: 92.3,
          loss: 0.156
        },
        {
          date: '2024-01-13 16:45',
          status: 'failed',
          params: { learningRate: 0.01, batchSize: 16 },
          accuracy: 88.7,
          loss: 0.234
        }
      ]
    }
  },
  mounted() {
    this.initComparisonChart()
  },
  beforeUnmount() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
  },
  methods: {
    resetParameters() {
      this.parameters = {
        learningRate: 0.001,
        batchSize: 32,
        epochs: 100,
        regularization: 0.01,
        dropout: 0.2,
        optimizer: 'adam'
      }
    },
    saveParameters() {
      alert('参数配置已保存！')
    },
    startOptimization() {
      alert('开始参数优化...')
    },
    applyRecommendation(configId) {
      if (configId === 1) {
        this.parameters.learningRate = 0.001
        this.parameters.batchSize = 64
        this.parameters.epochs = 100
      } else if (configId === 2) {
        this.parameters.learningRate = 0.0005
        this.parameters.batchSize = 128
        this.parameters.epochs = 150
      }
      alert(`已应用建议配置 #${configId}`)
    },
    
    initComparisonChart() {
      if (!this.$refs.performanceComparisonChart) return
      
      this.chartInstance = echarts.init(this.$refs.performanceComparisonChart)
      
      // 模拟不同配置的性能数据
      const configData = [
        {
          name: '基线模型',
          accuracy: 88.2,
          precision: 86.5,
          recall: 89.1,
          f1Score: 87.8,
          loss: 0.245
        },
        {
          name: '当前配置',
          accuracy: 92.4,
          precision: 91.2,
          recall: 93.6,
          f1Score: 92.4,
          loss: 0.178
        },
        {
          name: '推荐配置1',
          accuracy: 96.5,
          precision: 95.8,
          recall: 97.2,
          f1Score: 96.5,
          loss: 0.089
        },
        {
          name: '推荐配置2',
          accuracy: 95.8,
          precision: 95.1,
          recall: 96.5,
          f1Score: 95.8,
          loss: 0.103
        }
      ]
      
      const option = {
        title: {
          text: '参数配置性能对比',
          left: 'center',
          textStyle: {
            color: '#2c3e50',
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            let content = `<div style="font-weight: bold; margin-bottom: 8px;">${params[0].axisValue}</div>`
            params.forEach((param) => {
              content += `<div style="margin: 3px 0;">${param.marker} ${param.seriesName}: ${param.value}${param.seriesName === '损失值' ? '' : '%'}</div>`
            })
            return content
          }
        },
        legend: {
          data: ['准确率', '精确率', '召回率', 'F1分数', '损失值'],
          bottom: 10,
          textStyle: {
            color: '#2c3e50'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: configData.map(item => item.name),
          axisLabel: {
            color: '#7f8c8d',
            interval: 0,
            rotate: 15
          },
          axisLine: {
            lineStyle: {
              color: '#bdc3c7'
            }
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '性能指标 (%)',
            min: 80,
            max: 100,
            axisLabel: {
              color: '#7f8c8d',
              formatter: '{value}%'
            },
            axisLine: {
              lineStyle: {
                color: '#bdc3c7'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#ecf0f1'
              }
            }
          },
          {
            type: 'value',
            name: '损失值',
            min: 0,
            max: 0.3,
            position: 'right',
            axisLabel: {
              color: '#7f8c8d',
              formatter: '{value}'
            },
            axisLine: {
              lineStyle: {
                color: '#bdc3c7'
              }
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '准确率',
            type: 'bar',
            data: configData.map(item => item.accuracy),
            itemStyle: {
              color: '#3498db'
            },
            barWidth: '15%'
          },
          {
            name: '精确率',
            type: 'bar',
            data: configData.map(item => item.precision),
            itemStyle: {
              color: '#e74c3c'
            },
            barWidth: '15%'
          },
          {
            name: '召回率',
            type: 'bar',
            data: configData.map(item => item.recall),
            itemStyle: {
              color: '#27ae60'
            },
            barWidth: '15%'
          },
          {
            name: 'F1分数',
            type: 'bar',
            data: configData.map(item => item.f1Score),
            itemStyle: {
              color: '#f39c12'
            },
            barWidth: '15%'
          },
          {
            name: '损失值',
            type: 'line',
            yAxisIndex: 1,
            data: configData.map(item => item.loss),
            lineStyle: {
              color: '#9b59b6',
              width: 3
            },
            itemStyle: {
              color: '#9b59b6'
            },
            symbol: 'circle',
            symbolSize: 8
          }
        ]
      }
      
      this.chartInstance.setOption(option)
      
      // 响应式调整
      window.addEventListener('resize', () => {
        if (this.chartInstance) {
          this.chartInstance.resize()
        }
      })
    }
  }
}
</script>

<style scoped>
.parameter-optimization {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #7f8c8d;
  margin: 0;
}

.optimization-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.parameter-config,
.optimization-results {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.config-section,
.result-section {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.config-section h3,
.result-section h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
}

.parameter-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-bottom: 25px;
}

.param-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.param-item label {
  flex: 1;
  font-weight: 500;
  color: #2c3e50;
}

.param-item input,
.param-item select {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.param-value {
  flex: 0.5;
  font-weight: bold;
  color: #3498db;
}

.config-actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:hover {
  background: #2980b9;
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background: #7f8c8d;
}

.btn-success {
  background: #27ae60;
  color: white;
}

.btn-success:hover {
  background: #229954;
}

.btn-outline {
  background: transparent;
  border: 1px solid #3498db;
  color: #3498db;
}

.btn-outline:hover {
  background: #3498db;
  color: white;
}

.optimization-history {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #3498db;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.history-date {
  font-weight: 500;
  color: #2c3e50;
}

.history-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  text-transform: uppercase;
}

.history-status.completed {
  background: #d4edda;
  color: #155724;
}

.history-status.failed {
  background: #f8d7da;
  color: #721c24;
}

.history-details {
  color: #7f8c8d;
  font-size: 14px;
}

.history-details p {
  margin: 5px 0;
}

.performance-chart {
  height: 400px;
}

.chart-container {
  height: 100%;
  width: 100%;
  border-radius: 8px;
}

.recommendations {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.recommendation-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #27ae60;
}

.recommendation-item h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.config-details {
  margin-bottom: 15px;
}

.config-details p {
  margin: 5px 0;
  color: #7f8c8d;
  font-size: 14px;
}

.optimization-tips {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.tip-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #f39c12;
}

.tip-item h4 {
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.tip-item p {
  margin: 0;
  color: #7f8c8d;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .optimization-content {
    grid-template-columns: 1fr;
  }
  
  .param-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .config-actions {
    flex-direction: column;
  }
  
  .performance-chart {
    height: 300px;
  }
}

@media (max-width: 480px) {
  .parameter-optimization {
    padding: 10px;
  }
  
  .performance-chart {
    height: 250px;
  }
  
  .config-section,
  .result-section {
    padding: 15px;
  }
}
</style> 